<?php

namespace PKApp\Template;

use PKApp\Site\Classes\SiteService;
use PKCommon\Controller\AdminGetController;

class AdminGetTemplate extends AdminGetController
{
    protected $service_site;

    public function __construct()
    {
        parent::__construct();
        $this->service_site = new SiteService();
    }

    public function Main()
    {
        $this->fetch('template_list');
    }

    public function ApiByLists()
    {
        $path_site = $this->_getSitePath();
        $list_folder = ['block', 'content', 'form', 'style'];
        $list_entity = fileHelper()->OpenFolder($path_site);
        $list_result = [];
        foreach ($list_folder as $folder) {
            if (in_array($folder, $list_entity)) {
                $file_search = $folder == 'style' ? ['js', 'css'] : 'tpl';
                $list_result[] = [
                    'folder' => $folder,
                    'children' => fileHelper()->OpenFolder($path_site . $folder, $file_search),
                ];
            }
        }
        $this->json($list_result);
    }

    public function ApiBySelect()
    {
        $template_folder = request()->get('folder');
        $search_file = request()->get('query');
        $site_theme = $this->_getSitePath();
        $list_disk = fileHelper()->OpenFolder($site_theme . $template_folder, null, $search_file);
        $list_tpl = [];
        foreach ($list_disk as $item) {
            stristr($item['file_name'], '_m.') ?: $list_tpl[] = $item;
        }
        $this->json(
            $this->arrayToIdAndName($list_tpl, 'file_name', 'file_name')
        );
    }

    private function _getSitePath(): string
    {
        $site_entity = $this->service_site->interface_getEntityById(
            $this->loginUser()->SiteId, ['setting']
        );
        $site_theme = PATH_ROOT . 'Templates' . DS . $site_entity['setting']['Site_Themes'] . DS;
        file_exists($site_theme) ?: $this->noticeByJson('template_PathNotExists', 'template');
        return $site_theme;
    }
}